import React, { useState } from 'react';
import { EditorState, convertToRaw, ContentState } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';

type Props = {
    editorRef: React.MutableRefObject<(() => string) | null>;
    detail: string | false;
};

/* 商品详情富文本编辑器 */
const RichTextEditor: React.FC<Props> = ({ editorRef, detail }) => {
    const [editorState, setEditorState] = useState<EditorState>(
        detail
            ? EditorState.createWithContent(
                ContentState.createFromBlockArray(
                    htmlToDraft(detail).contentBlocks
                )
            )
            : EditorState.createEmpty()
    );
    const uploadImageCallBack = (file: any): Promise<{
        data: { link: string }
    }> => {
        return new Promise(
            (resolve, reject) => {
                const xhr: XMLHttpRequest = new XMLHttpRequest();
                xhr.open('POST', '/api1/manage/img/upload');
                xhr.setRequestHeader('Authorization', 'Client-ID XXXXX');
                const data: FormData = new FormData();
                data.append('image', file);
                xhr.send(data);
                xhr.addEventListener('load', () => {
                    const response = JSON.parse(xhr.responseText);
                    const { url } = response.data;
                    resolve({
                        data: { link: url }
                    });
                });
                xhr.addEventListener('error', () => {
                    const error = JSON.parse(xhr.responseText);
                    reject(error);
                });
            }
        );
    };
    const onEditorStateChange = (editorState: EditorState): void => {
        setEditorState(editorState);
    };
    const getDetail = (): string => draftToHtml(convertToRaw(editorState.getCurrentContent()));
    editorRef.current = getDetail;
    return (
        <Editor
            editorState={editorState}
            editorStyle={{ border: '1px solid #333', paddingLeft: 10, height: 200 }}
            onEditorStateChange={onEditorStateChange}
            toolbar={{
                image: { uploadCallback: uploadImageCallBack, alt: { present: true, mandatory: true } }
            }}
        />
    );
};

export default RichTextEditor;